<?php
namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\models\MerchantPayment;
use app\modules\admin\forms\merchant\MerchantPaymentForm;
use yii\helpers\Json;

class MerchantPaymentService extends BaseService{

    /**
     * 获取信息
     * @param $id
     * @return MerchantPayment|mixed|null
     */
    public static function getInfoById($id){
        $model = MerchantPayment::findOne($id);
        if(!$model){
            return $model;
        }
        $config = $model->getConfig();
        $config['merchant_id'] = $id;
        return $config;
    }

    /**
     * 更新
     * @param MerchantPaymentForm $form
     * @return bool
     */
    public static function update(MerchantPaymentForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }
        $model = MerchantPayment::findOne($form->merchant_id);
        if(!$model){
            $model = new MerchantPayment();
            $model->setAttribute("merchant_id",$form->merchant_id);
        }

        $model->setAttribute("config",Json::encode($form->getAttributes(['mch_no','sign_key','mach_no'])));
        return $model->save();
    }

    /**
     * 删除
     * @param $id
     */
    public static function delete($id){
        MerchantPayment::deleteAll(['merchant_id'=>$id]);
    }
}